package jp.co.systemi.asp.workflow.cron;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jp.co.systemi.asp.workflow.data.Reminder;
import jp.co.systemi.asp.workflow.data.ReminderMeta;
import jp.co.systemi.asp.workflow.mail.Mail;

import org.slim3.datastore.Datastore;

public class SendReminderMail extends HttpServlet {
    private static final Logger log = Logger.getLogger(SendReminderMail.class
            .getName());
    private static final long serialVersionUID = -1574055166182829807L;
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        ReminderMeta rm = ReminderMeta.get();
        List<Reminder> reminders = Datastore.query(rm).filter(rm.sendFlg.notEqual(true)).asList();
        Calendar cal = Calendar.getInstance();
        Date today = cal.getTime();
        int i = 0;
        for(Reminder reminder : reminders){
            log.info("reminder date: " + sdf.format(reminder.getReminderDate()));
            if(sdf.format(reminder.getReminderDate()).compareTo(sdf.format(today)) <= 0){

                // メール送信
                Mail mail = new Mail();

                mail.sendReminderMail(reminder);

                reminder.setSendFlg(true);
                Datastore.put(reminder);

                log.info("リマインダーメール送信：" + reminder.toString());
                i++;
            }
        }
        log.info("リマインダーメール　" + i + " 件を送信しました。");
    }

}
